<?php

/**
 * User: Allen
 * Date: 15-10-12
 * 会员控制器
 */

class User extends PC_Controller
{
    protected $go_url = '/admin/user/user_list';
    public function __construct()
    {
        parent::__construct();
        $this->load->model('user_model');
        $this->load->model('area_model');
    }

    /**
     * @brief 会员列表页面
     * @param Null
     * @par 2015/10/12 Ver 1.00 Created by Allen
     */
    public function user_list()
    {

        $this->data['username'] =  empty($_POST) ? '' : $_POST['username'];
        $this->data['phone'] =  empty($_POST) ? '' : $_POST['phone'];
        $this->data['parent_id'] =  empty($_GET) ? '' : $_GET['id'];
        $this->data['start_time'] = empty($_POST['start_time']) ? '' : $_POST['start_time'];
        $this->data['end_time'] = empty($_POST['end_time']) ? '' : $_POST['end_time'];
        if ($this->admin['admin_type'] == 'user' && !$this->data['parent_id']) {
            $_GET['parent_id'] =  $this->admin['id'];
        }
        $where = array();
        $this->data['username'] ? $where['user.username like'] = '%' . trim($this->data['username']) . '%' : '';
        $this->data['phone'] ? $where['user.phone like'] = '%' . trim($this->data['phone']) . '%' : '';
        $this->data['parent_id'] ? $where['user.parent_id'] = $this->data['parent_id'] : '';
        $this->data['start_time'] ? $where['user.s_time >='] = strtotime($this->data['start_time']) : '';
        $this->data['end_time'] ? $where['user.s_time <='] = strtotime($this->data['end_time']) : '';
        //$this->data['id']?$where['user.id']=$data['id']:'';
        $group_performance = $this->user_model->select('sum(price) as group_performance')->where($where)->find();
        $this->data['group_performance'] = $group_performance['group_performance'];
        $add = $this->Isallow('user', 'add');
        $this->data['add'] = $add;
        $this->data['id'] =  empty($_GET['parent_id']) ? '' : $_GET['parent_id'];
        $message = $this->uri->segment(4);
        $this->data['message'] = $message;
        if ($this->admin['admin_type'] == 'user' && $this->admin['password'] == 'e10adc3949ba59abbe56e057f20f883e') {
            $message = 7;
        }
        $this->data['admin_type'] = $this->admin['admin_type'];
        $this->load->view('/admin/user_list.php', $this->data);
    }

    /**
     * @brief ajxa获取会员列表数据
     * @param Null
     * @par 2015/10/12 Ver 1.00 Created by Allen
     */
    public function ajax_user_list()
    {

        $data = $_GET;
        $start = $data['iDisplayStart']; //显示的起始索引
        $length = $data['iDisplayLength']; //显示的行数
        $sort_th = $data['mDataProp_' . $data['iSortCol_0'] . '']; //被排序的列
        $sort_type = $data['sSortDir_0']; //排序的方向 "desc" 或者 "asc".
        $search = $data['sSearch']; //全局搜索字段
        $data['username'] ? $where['user.username like'] = '%' . trim($data['username']) . '%' : '';
        $data['phone'] ? $where['user.phone like'] = '%' . trim($data['phone']) . '%' : '';
        $data['parent_id'] ? $where['user.parent_id'] = $data['parent_id'] : '';
        $data['start_time'] ? $where['user.s_time >='] = strtotime($data['start_time']) : '';
        $data['end_time'] ? $where['user.s_time <='] = strtotime($data['end_time']) : '';
        $data['id'] ? $where['user.id'] = $data['id'] : '';
        $where['concat(user.id) like'] = '%' . trim($search) . '%';
        $this->data['count'] = $this->user_model->getCount($where);
        //$group_performance=$this->user_model->select('sum(price) as group_performance')->find();
        $aaData = array();
        if ($this->data['count']) {
            $order_by = $sort_th . " " . $sort_type;
            $user_list = $this->user_model->getUserList($where, $length, $start, $order_by);
            //echo $this->db->last_query();
            $this->load->model('user_level_model');
            $user_tmp = array();
            $add_next_status = $this->Isallow('user', 'add_next');
            $tixian_status = $this->Isallow('cash', 'add_page');
            $system_money_status = $this->Isallow('system_money', 'add_page');
            $zhuan_system_status = false;
            $zhuan_system_status = $this->Isallow('system_zhuan', 'add_page');


            $authority = $this->authority;
            foreach ($user_list as $key => $value) {
                // $user_list[$key]['group_performance']=$group_performance['group_performance'];
                if ($value['parent_id']) {
                    if (in_array($value['parent_id'], $user_tmp)) {
                        $user_list[$key]['parent_name'] = $user_tmp[$value['parent_id']]['parent_name'];
                        $user_list[$key]['parent_nick'] = $user_tmp[$value['parent_id']]['user_nick'];
                    } else {
                        $user = $this->user_model->checkUser(array('user.id' => $value['parent_id']));
                        $user_tmp[$value['parent_id']]['parent_name'] = $user['username'];
                        $user_tmp[$value['parent_id']]['user_nick'] = $user['user_nick'];
                        $user_list[$key]['parent_name'] = $user_tmp[$value['parent_id']]['parent_name'];
                        $user_list[$key]['parent_nick'] = $user_tmp[$value['parent_id']]['user_nick'];
                    }
                } else {
                    $user_list[$key]['parent_name'] = '无';
                    $user_list[$key]['parent_nick'] = '无';
                }
                if (!$value['color']) {
                    $value['color'] = 'green';
                }
                $user_list[$key]['user_level_name'] = '<b style="color:' . $value['color'] . ';">' . $value['user_level_name'] . '</b>';
                $user_list[$key]['create_time'] = date('Y-m-d', $value['create_time']);
                $user_list[$key]['s_time'] = date('Y-m-d', $value['s_time']);
                $port = unserialize($value['areas']);
                $user_list[$key]['areas'] = $port['detail'] . $value['address'];
                $user_list[$key]['avatar'] = '<img src = "' . $value['avatar'] . '" style="height:30px;"/>';
                $edit_url = '';
                if ($authority['edit_status'] == 2) {

                    if ($this->admin['admin_type'] == 'admin' || $value['id'] == $this->admin['id']) {
                        $edit_url = '<a href="/admin/user/edit_page/?id=' . $value['id'] . '" title="修改会员信息"><span class="btn btn-xs btn-primary">编辑</span></a>';
                    }
                }
                $del_url = '';
                if ($authority['del_status'] == 2) {
                    //$del_oper = "onclick=\"if(confirm('确实要删除此条记录吗？')) return true;else return false; \"";
                    //$del_url = '<a href="/admin/user/delete/?id='.$value['id'].'"  '.$del_oper.'><span class="btn btn-xs btn-danger cancel">删除</span></a>';
                }
                $system_zhuan = '';
                if ($zhuan_system_status) {
                    if ($this->admin['admin_type'] == 'user') {
                        if ($value['id'] == $this->admin['id']) {
                            $system_zhuan = '<a href="/admin/system_zhuan/add_page/?user_id=' . $value['id'] . '" title="会员之间互相转账"><span class="btn btn-xs btn-pink">转账</span></a>';
                        }
                    } else {
                        if (isset($_GET['parent_id']) &&  $_GET['parent_id']) {
                            $system_zhuan = '';
                        } else {
                            $system_zhuan = '<a href="/admin/system_zhuan/add_page/?user_id=' . $value['id'] . '" title="会员之间互相转账"><span class="btn btn-xs btn-pink">转账</span></a>';
                        }
                    }
                }
                $add_next = '';
                if ($this->admin['admin_type'] == 'user') {
                    $add_next_status = false;
                }
                $zhuangtai_url = '';
                if ($add_next_status) {
                    $add_next = '<a href="/admin/user/add_next/?id=' . $value['id'] . '"  title="推荐自己的下级"><span class="btn btn-xs btn-pink">推荐</span></a>';
                    if ($value['zhuangtai'] == '已锁定') {
                        $zhuangtai_url = '<a href="javascript:void(0)" onclick="zhuangtai(' . $value['id'] . ',\'/user/zhuangtai\',\'解锁\',\'' . $value['username'] . '\')"  title="解锁"><span class="btn btn-xs btn-info">解锁</span></a>';
                    } else {
                        $zhuangtai_url = '<a href="javascript:void(0)" onclick="zhuangtai(' . $value['id'] . ',\'/user/zhuangtai\',\'锁定\',\'' . $value['username'] . '\')"   title="锁定"><span class="btn btn-xs btn-danger">锁定</span></a>';
                    }
                }
                $tixian_text = '';
                if ($tixian_status) {
                    if ($this->admin['admin_type'] == 'user') {
                        if ($value['id'] == $this->admin['id']) {
                            $tixian_text = '<a href="/admin/cash/add_page/?user_id=' . $value['id'] . '" title="账户余额提现"><span class="btn btn-xs btn-warning">提现</span></a>';
                        }
                    } else {
                        $tixian_text = '<a href="/admin/cash/add_page/?user_id=' . $value['id'] . '" title="账户余额提现"><span class="btn btn-xs btn-warning">提现</span></a>';
                    }
                }

                $system_money_text = '';
                if ($system_money_status) {
                    if ($this->admin['admin_type'] == 'user') {
                        if ($value['id'] == $this->admin['id']) {
                            $system_money_text = '<a href="/admin/system_money/add_page/?user_id=' . $value['id'] . '"><span class="btn btn-xs btn-focus">转报单币</span></a>';
                        }
                    } else {
                        $system_money_text = '<a href="/admin/system_money/add_page/?user_id=' . $value['id'] . '"><span class="btn btn-xs btn-focus">转报单币</span></a>';
                    }
                }
                if ($this->admin['admin_type'] == 'admin' && $this->Isallow('user', 'addprice')) {
                    $del_url = '<a onclick="chargeOne(' . $value['id'] . ',\'/user/addprice\',\'' . $value['username'] . '\',\'' . $value['price'] . '\')"  data_id = ' . $value['id'] . '><span class="btn btn-xs btn-purple">回填</span></a>';
                }

                $view_url = '<a href="/admin/user/user_list/?id=' . $value['id'] . '"><span class="btn btn-xs btn-success">查看</span></a>';
                $team_url = '';
                if ($this->admin['admin_type'] == 'admin') {
                    $team_url = '<a href="/admin/user/team_page/?id=' . $value['id'] . '"><span class="btn btn-xs btn-success">查看团队</span></a>';
                }
                $guquan_url = '';
                $edit_parent_url = '';

                if ($this->admin['admin_type'] == 'admin') {
                    $guquan_url = '<a href="/admin/user/guquan/?id=' . $value['id'] . '"><span class="btn btn-xs btn-danger">报股权</span></a>';
                    if ($value['update_parent'] == 1) {
                        $edit_parent_url = '<a onclick="editParent(' . $value['id'] . ',\'' . $value['username'] . '\')" href="javascript:void(0);"><span class="btn btn-xs btn-default">高管独立</span></a>';
                    }
                }
                $zhunru_url = '<a href="/admin/system_zhuan/index?tousername=' . $value['username'] . '"><span class="btn btn-xs btn-primary">转入记录</span></a>';

                $user_list[$key]['operate'] = $edit_url . " " . $del_url . " " . $view_url . " " . $team_url . " " . $add_next . " " . $zhuangtai_url . " " . $tixian_text . ' ' . $system_money_text . ' ' . $system_zhuan . ' ' . $zhunru_url . ' ' . $guquan_url . ' ' . $edit_parent_url;
            }
            $aaData = $user_list;
        }
        $output['aaData'] = $aaData;
        $output['sEcho'] = $_GET['sEcho'];
        $output['iTotalDisplayRecords'] =  $this->data['count']; //总共有几条数据
        $output['iTotalRecords'] = $this->data['count']; //总共有几条数据
        echo json_encode($output); //最后把数据以json格式返回
    }

    public function zhuangtai()
    {
        $id = $_POST['id'];
        $result = array();
        if ($id) {
            $user = $this->user_model->select('zhuangtai')->where(array('id' => $id))->find();
            if ($user) {
                $updateData = array();
                if ($user['zhuangtai'] == '已锁定') {
                    $updateData['zhuangtai'] = '已解锁';
                } else {
                    $updateData['zhuangtai'] = '已锁定';
                }
                $this->user_model->editUser(array('id' => $id), $updateData);
                $result['error'] = '操作成功';
                $result['success'] = 1;
            } else {
                $result['error'] = '用户不存在';
                $result['success'] = 0;
            }
        } else {
            $result['error'] = 'ID不能为空';
            $result['success'] = 0;
        }
        echo json_encode($result);
    }
    /** 
     * some_func  
     *报股权页面
     * 
     * @access public 
     * @param mixed 
     * @param mixed 
     * @param mixed 
     * @since 1.0 
     * @return array 
     */
    public function guquan()
    {
        $this->data['id'] = $_GET['id'];
        $this->data['authority'] = $this->authority;
        $this->data['message'] = '1';
        //读取文件获取设置的等级分润比例
        $this->load->model('guquan_level_model');
        $guquan_level = $this->guquan_level_model->getGuquanLevelList();
        $this->data['guquan_level'] = $guquan_level;
        $this->load->view('/admin/guquan', $this->data);
    }
    /** 
     * some_func  
     * 获取当前用户的所有直接上级
     * 
     * @access public 
     * @param mixed 
     * @param mixed 
     * @param mixed 
     * @since 1.0 
     * @return array 
     */
    public function ajax_guquan_list()
    {

        $aaData = array();
        $where = array('id' => $_GET['id']);
        $user = $this->user_model->checkUser($where);
        //echo "<pre>";$this->db->last_query();print_r($user);exit;
        $user_list = array();
        if (isset($user['parent_path']) && $user['parent_path']) {
            $user_list = $this->user_model->getUserAll('user.id in (' . $user['parent_path'] . ')', 'user.id desc');
            //echo $this->db->last_query();exit;
        }
        $user_tmp = array();
        $level_cengji = array();
        foreach ($user_list as $key => $value) {
            if ($key != 0) {
                if (isset($level_cengji[$value['user_level']])) {
                    $level_cengji[$value['user_level']] = $level_cengji[$value['user_level']] + 1;
                } else {
                    $level_cengji[$value['user_level']] = 1;
                }
            } else {
                $level_cengji[$value['user_level']] = 0;
            }

            $user_list[$key]['check'] = '<label><input name="c_id" user_level="' . $value['user_level'] . '" cengji="' . $level_cengji[$value['user_level']] . '" type="checkbox" value="' . $value['id'] . '" /></label>';
            $user_list[$key]['cengji_name'] = '直线<b style="color:' . $value['color'] . ';">' . $level_cengji[$value['user_level']] . '</b>级' . $value['user_level_name'];
            // $user_list[$key]['group_performance']=$group_performance['group_performance'];
            if ($value['parent_id']) {
                if (in_array($value['parent_id'], $user_tmp)) {
                    $user_list[$key]['parent_name'] = $user_tmp[$value['parent_id']]['parent_name'];
                    $user_list[$key]['parent_nick'] = $user_tmp[$value['parent_id']]['user_nick'];
                } else {
                    $user = $this->user_model->checkUser(array('user.id' => $value['parent_id']));
                    $user_tmp[$value['parent_id']]['parent_name'] = $user['username'];
                    $user_tmp[$value['parent_id']]['user_nick'] = $user['user_nick'];
                    $user_list[$key]['parent_name'] = $user_tmp[$value['parent_id']]['parent_name'];
                    $user_list[$key]['parent_nick'] = $user_tmp[$value['parent_id']]['user_nick'];
                }
            } else {
                $user_list[$key]['parent_name'] = '无';
                $user_list[$key]['parent_nick'] = '无';
            }
            if (!$value['color']) {
                $value['color'] = 'green';
            }
            $user_list[$key]['user_level_name'] = '<b style="color:' . $value['color'] . ';">' . $value['user_level_name'] . '</b>';
            $user_list[$key]['create_time'] = date('Y-m-d', $value['create_time']);
            $user_list[$key]['s_time'] = date('Y-m-d', $value['s_time']);
            $port = unserialize($value['areas']);
            $user_list[$key]['areas'] = $port['detail'] . $value['address'];
            $user_list[$key]['avatar'] = '<img src = "' . $value['avatar'] . '" style="height:30px;"/>';
            $edit_url = '';
            $user_list[$key]['fenru_bili'] = '<input style="max-width:80px;" type="number" onBlur="jisuan_fenrun(this)" user_id="' . $value['id'] . '" name="fenru_bili_' . $value['id'] . '" id="fenru_bili_' . $value['id'] . '"/>';
            $user_list[$key]['bonus_money'] = '<input style="max-width:100px;" type="text" name="bonus_money_' . $value['id'] . '" id="bonus_money_' . $value['id'] . '"/>';
            $user_list[$key]['remark'] = '<input type="text" user_level="' . $value['user_level_name'] . '" system_money="' . $value['system_balance'] . '" name="remark_' . $value['id'] . '" id="remark_' . $value['id'] . '"/>';
            $team_url = '';
            if ($this->admin['admin_type'] == 'admin') {
                $team_url = '<a href="/admin/user/team_page/?id=' . $value['id'] . '"><span class="btn btn-xs btn-success">查看团队</span></a>';
            }
            if (isset($user_list[0]['id']) && $user_list[0]['id']) {
                $user_list[$key]['operate'] = $team_url;
                if ($user_list[0]['parent_id']) {
                }
            }
        }

        $aaData = array_reverse($user_list);
        $output['aaData'] = $aaData;
        $output['sEcho'] = $_GET['sEcho'];
        $output['iTotalDisplayRecords'] =  count($aaData); //总共有几条数据
        $output['iTotalRecords'] = count($aaData); //总共有几条数据
        echo json_encode($output); //最后把数据以json格式返回
    }
    public function doGuquan()
    {
        $user = $this->user_model->checkUser(array('username' => $_POST['chuzhang_name']));
        $bonus_log = array();
        $this->db->trans_start();
        $ids = explode(',', $_POST['checids']);
        $pici = time();
        $this->load->model('bonus_log_model');
        foreach ($ids as $key => $value) {
            if ($value) {
                $bonus_log = array();
                //bonus_money_316  remark_316
                $to_user_id = $value;
                $touser = $this->user_model->checkUser(array('id' => $to_user_id));
                $bonus_money = $_POST['bonus_money_' . $to_user_id];
                $from_yue = $user['system_balance'] - $bonus_money;
                $feiyong = $bonus_money * 0.05;
                $shiji_money = $bonus_money * 0.95;
                $yue = $touser['system_balance'] + $shiji_money;
                //先处理出账人报单币
                $sql = "update `user` set system_balance = system_balance - " . $bonus_money . ' where id =' . $user['id'];
                $this->db->query($sql);
                //处理报单币日志
                $logdata[] = array(
                    'user_id' => $user['id'],
                    'username' => $user['username'],
                    'true_name' => $user['true_name'],
                    'money' => '-' . $bonus_money,
                    'type' => 'guquan',
                    'remark' => $user['true_name'] . '您于' . date('Y-m-d H:i:s', time()) . "给" . $touser['username'] . '股权分润' . $bonus_money . "元.余额" . $from_yue,
                    'create_time' =>  time()
                );
                $this->add_system_money_log($logdata);
                unset($logdata);
                //处理分红人的报单币金额
                $sql = "update `user` set system_balance = system_balance + " . $shiji_money . ' where id =' . $to_user_id;
                $this->db->query($sql);
                //处理报单币日志
                $logdata[] = array(
                    'user_id' => $touser['id'],
                    'username' => $touser['username'],
                    'true_name' => $touser['true_name'],
                    'money' => $shiji_money,
                    'type' => 'guquan',
                    'feiyong' => $feiyong,
                    'remark' => $touser['username'] . '您于' . date('Y-m-d H:i:s', time()) . "收到" . $user['username'] . '的股权分润' . $bonus_money . "元,扣除费用" . $feiyong . '实际到账' . $shiji_money . '.余额' . $yue,
                    'bonus_remark' => $_POST['remark_' . $value],
                    'create_time' =>  time()
                );
                $this->add_system_money_log($logdata);
                unset($logdata);
                //记录分红日志
                $bonus_log['money']         = $bonus_money;
                $bonus_log['shiji_money']   = $shiji_money;
                $bonus_log['feiyong']       = $feiyong;
                $bonus_log['pici']              = $pici;
                $bonus_log['create_time']       = time();
                $bonus_log['remark']       = $_POST['remark_' . $value];
                $bonus_log['chuzhang']      = $user['username'];
                $bonus_log['user_name'] = $touser['username'];
                $bonus_log['chuzhuang_id'] = $user['id'];
                $bonus_log['user_id'] = $touser['id'];
                $bonus_log['type'] = 'guquan';
                $this->bonus_log_model->addBonusLog($bonus_log);
            }
        }
        $this->db->trans_complete();
        $this->location_href($this->go_url . "/4");
        exit;
    }

    /**
     * @brief 进入编辑页面
     * @param Null
     * @par 2015/10/12 Ver 1.00 Created by Allen
     */
    public function edit_page()
    {
        $where['id'] = $_GET['id'];
        if ($this->admin['admin_type'] == 'user' && $_GET['id'] != $this->admin['id']) {
            $this->location_href($this->go_url . "/3");
            exit;
        }
        $user_info = $this->user_model->checkUser($where);

        if (!$user_info['s_time']) {
            $user_info['s_time'] = $user_info['create_time'];
        }
        $this->load->model('fora_log_model');
        $fora_info = $this->fora_log_model->checkForaLog(array('code' => $user_info['csg']));
        if (isset($fora_info['id']) && $fora_info['id']) {
            $user_info['fora_id'] = $fora_info['id'];
        } else {
            $user_info['fora_id'] = 0;
        }
        $user_info['s_time'] = date('Y-m-d H:i:s', $user_info['s_time']);
        $areas = unserialize($user_info['areas']);
        $area_array = explode(',', $areas['area_no']);
        if (count($area_array) != 3) {
            $area_array[0] = '110000';
            $area_array[1] = '111000';
            $area_array[2] = '110101';
        }
        $province_area = $area_array[0];
        $city_area = $area_array[1];
        $area_where['parentno'] = 0;
        $area_list = $this->area_model->getArealist($area_where);
        $city_list = $this->area_model->getArealist(array('parentno' => $province_area, 'arealevel' => 2));
        $county_list = $this->area_model->getArealist(array('parentno' => $city_area, 'arealevel' => 3));
        $this->data['area_list'] = $area_list;
        $this->data['admin_type'] = $this->admin['admin_type'];
        $this->data['city_list'] = $city_list;
        $this->data['county_list'] = $county_list;
        $this->data['area_array'] = $area_array;
        $this->data['data'] = $user_info;
        $this->getFora();
        $this->load->view('/admin/user_edit', $this->data);
    }

    /**
     * @brief 获取联动城市
     * @param Null
     * @par 2015/10/12 Ver 1.00 Created by Allen
     */
    public function city()
    {
        $id = $this->uri->segment(4);
        $city_list = $this->area_model->getArealist(array('parentno' => $id, 'arealevel' => 2));
        $county_list = $this->area_model->getArealist(array('parentno' => $city_list[0]['areano'], 'arealevel' => 3));
        $city = '';
        $county = '';
        foreach ($city_list as $value) {
            $city .= ' <option value="' . $value['areano'] . ',' . $value['areaname'] . '">' . $value['areaname'] . '</option>';
        }
        foreach ($county_list as $value) {
            $county .= ' <option value="' . $value['areano'] . ',' . $value['areaname'] . '">' . $value['areaname'] . '</option>';
        }
        $data['city'] = $city;
        $data['county'] = $county;
        echo json_encode($data);
    }

    /**
     * @brief 获取联动区域
     * @param Null
     * @par 2015/10/12 Ver 1.00 Created by Allen
     */
    public function county()
    {
        $id = $_GET['id'];
        $county_list = $this->area_model->getArealist(array('parentno' => $id, 'arealevel' => 3));
        $county = '';
        foreach ($county_list as $value) {
            $county .= ' <option value="' . $value['areano'] . ',' . $value['areaname'] . '">' . $value['areaname'] . '</option>';
        }
        $data['county'] = $county;
        echo json_encode($data);
    }

    /**
     * @brief 保存编辑信息
     * @param Null
     * @par 2015/10/12 Ver 1.00 Created by Allen
     */
    public function edit()
    {
        if (isset($_POST['fora_id'])) {
            unset($_POST['fora_id']);
        }
        if ($this->admin['admin_type'] == 'user' && $_POST['id'] != $this->admin['id']) {
            $this->location_href($this->go_url . "/3");
            exit;
        }
        if ($_POST['password']) {
            $_POST['password'] = md5($_POST['password']);
        } else {
            unset($_POST['password']);
        }
        if ($_POST['password2']) {
            $_POST['password2'] = md5($_POST['password2']);
        } else {
            unset($_POST['password2']);
        }
        if ($_POST['newusername'] && $_POST['newusername'] != $_POST['username']) {
            $_POST['username'] = $_POST['newusername'];
            unset($_POST['newusername']);
        } else {
            unset($_POST['newusername']);
            unset($_POST['username']);
        }
        $_POST['s_time'] = strtotime($_POST['s_time']);
        $data = $_POST;
        $data = $this->get_post($data, 'areas');
        $data['update_time'] = time();
        $where['id'] = $data['id'];

        //查找之前的code供位编号 然后更新
        if ($this->admin['admin_type'] == 'admin') {
            $user_info = $this->user_model->checkUser($where);
            if ($user_info['csg'] != $data['csg']) {
                $this->load->model('fora_log_model');
                $fora_log = $this->fora_log_model->checkForaLog(array('code' => $data['csg']));
                if (isset($fora_log) && !empty($fora_log) && isset($fora_log['id']) && $fora_log['id']) {
                    $this->fora_log_model->editForaLog(array('id' => $fora_log['id']), array('status' => 2, 'update_time' => time(), 'user_id' => $data['id'], 'use_time' => time(), 'username' => $user_info['username']));
                    $this->fora_log_model->editForaLog(array('code' => $user_info['csg']), array('status' => 1, 'update_time' => time(), 'user_id' => '0', 'use_time' => '', 'username' => ''));
                }
            }
        }
        $edit_result = $this->user_model->editUser($where, $data);
        if ($edit_result) {
            $this->location_href($this->go_url . "/2");
        } else {
            $this->location_href($this->go_url . "/3");
        }
    }

    /**
     * @brief 删除会员信息
     * @param Null
     * @par 2015/10/12 Ver 1.00 Created by Allen
     */
    public function delete()
    {
        $id = $this->uri->segment(4);
        $where['id'] = $id;
        $del_result = $this->user_model->deleteUser($where);
        $go_url = '/admin/user/user_list';
        if ($edit_result) {
            $this->location_href($this->go_url . "/2");
        } else {
            $this->location_href($this->go_url . "/3");
        }
    }

    /**
     * @brief 进入详情页面
     * @param Null
     * @par 2015/10/12 Ver 1.00 Created by Allen
     */
    public function view_page()
    {
        $id = $this->uri->segment(4);
        $where['id'] = $id;
        $user_info = $this->user_model->checkUser($where);
        $areas = unserialize($user_info['areas']);
        $user_info['areas'] = $areas['detail'];
        $this->data['data'] = $user_info;
        $this->load->view('/admin/user_view', $this->data);
    }
    /**
     * 添加会员
     */
    public function add_page()
    {
        //查找后台设置的报单价格
        $this->load->model('system_config_model');
        $system_config = $this->system_config_model->checkSystem_config(array('id' => '1'));
        $area_array = array();
        if (count($area_array) != 3) {
            $area_array[0] = '110000';
            $area_array[1] = '111000';
            $area_array[2] = '110101';
        }
        $province_area = $area_array[0];
        $city_area = $area_array[1];
        $area_where['parentno'] = 0;
        $area_list = $this->area_model->getArealist($area_where);
        $city_list = $this->area_model->getArealist(array('parentno' => $province_area, 'arealevel' => 2));
        $county_list = $this->area_model->getArealist(array('parentno' => $city_area, 'arealevel' => 3));
        $this->data['area_list'] = $area_list;
        $this->data['city_list'] = $city_list;
        $this->data['county_list'] = $county_list;
        $this->data['next_add'] = '0';
        $this->data['parent_id'] = '0';
        $this->data['parent_true_name'] = '总部';
        $this->data['area_array'] = $area_array;
        $this->data['error_msg'] = false;
        $this->data['system_config'] = $system_config;
        $this->data['is_admin'] = $this->admin['admin_type'];
        $this->data['zhuangtai'] = '已锁定';
        $this->data['now_time'] = date("Y-m-d H:i:s", time());
        $this->getFora();
        $this->load->view('/admin/user_add',  $this->data);
    }
    /**
     * 添加会员下级
     */
    public function add_next()
    {
        $id = $_GET['id'];
        $this->load->model('system_config_model');
        $system_config = $this->system_config_model->checkSystem_config(array('id' => '1'));
        $error_msg = false;
        $user_info = $this->user_model->checkUser(array('id' => $id));

        if ($this->admin['admin_type'] == 'user' && $id != $this->admin['id']) {
            $error_msg = '无法替别人报单';
        }
        if ($id == $this->admin['id'] && $this->admin['admin_type'] == 'user') {

            //查找当前用户数据
            //查找后台设置的报单价格


            if (intval($user_info['system_balance']) < intval($system_config['price'])) {
                $error_msg = '报单币不足';
            }
        }
        $area_array = array();
        if (count($area_array) != 3) {
            $area_array[0] = '110000';
            $area_array[1] = '111000';
            $area_array[2] = '110101';
        }
        $province_area = $area_array[0];
        $city_area = $area_array[1];
        $area_where['parentno'] = 0;
        $area_list = $this->area_model->getArealist($area_where);
        $city_list = $this->area_model->getArealist(array('parentno' => $province_area, 'arealevel' => 2));
        $county_list = $this->area_model->getArealist(array('parentno' => $city_area, 'arealevel' => 3));
        $this->data['error_msg'] = $error_msg;
        $this->data['area_list'] = $area_list;
        $this->data['city_list'] = $city_list;
        $this->data['county_list'] = $county_list;
        $this->data['parent_id'] = $user_info['id'];
        $this->data['parent_true_name'] = $user_info['true_name'];
        $this->data['next_add'] = '1';
        $this->data['system_config'] = $system_config;
        $this->data['now_time'] = date("Y-m-d H:i:s", time());
        $this->data['area_array'] = $area_array;
        $this->data['is_admin'] = $this->admin['admin_type'];
        $this->data['zhuangtai'] = $user_info['zhuangtai'];
        $this->getFora();
        $this->load->view('/admin/user_add',  $this->data);
    }
    /**
     * 添加用户
     */
    public function add()
    {
        $this->check_param();

        $_POST['password'] = md5($_POST['password1']);
        $_POST['password2'] = md5($_POST['password2']);
        $_POST['s_time'] =  strtotime($_POST['s_time']);
        if (isset($_POST['fora_id'])) {
            unset($_POST['fora_id']);
        }
        if (isset($_POST['zhuangtai'])) {
            if ($_POST['zhuangtai']) {
                $_POST['zhuangtai'] = '已解锁';
            } else {
                $_POST['zhuangtai'] = '已锁定';
            }
        } else {
            $_POST['zhuangtai'] = '已锁定';
        }
        $asjs = $_POST['asjs'];
        unset($_POST['asjs']);
        $data = $_POST;
        $data['create_time'] = time();
        $data = $this->get_post($data, 'areas');
        $this->load->model('user_level_model');
        $user_level = $this->user_level_model->checkUserLevel(array('is_default' => '1'));
        $data['user_level'] = $user_level['id'];


        $add_result = $this->user_model->addUser($data);
        if ($this->admin['admin_type'] == 'admin') {
            $this->load->model('fora_log_model');
            $fora_log = $this->fora_log_model->checkForaLog(array('code' => $data['csg']));
            if (isset($fora_log) && !empty($fora_log) && isset($fora_log['id']) && $fora_log['id']) {
                $this->fora_log_model->editForaLog(array('id' => $fora_log['id']), array('status' => 2, 'update_time' => time(), 'user_id' => $add_result, 'use_time' => time(), 'username' => $data['username']));
            }
        }

        $user = array();
        $parent_user = array();
        $parent_parent_user = array();
        if ($add_result) {
            $user = $this->user_model->checkUser(array('id' => $add_result));
            if ($_POST['parent_id']) {

                $parent_user = $this->user_model->checkUser(array('id' => $_POST['parent_id']));

                if ($_POST['parent_id'] && $this->admin['admin_type'] == 'user') {
                    $this->load->model('system_config_model');
                    $system_config = $this->system_config_model->checkSystem_config(array('id' => '1'));
                    $system_balance = $parent_user['system_balance'] - $system_config['price'];
                    $puserUpdata = array('system_balance' => $system_balance);

                    $this->user_model->editUser(array('id' => $_POST['parent_id']), $puserUpdata);
                    //记录日志
                    $money_logdata[] = array(
                        'user_id' => $parent_user['id'],
                        'username' => $parent_user['username'],
                        'true_name' => $parent_user['true_name'],
                        'money' => $system_config['price'],
                        'type' => 'adduser',
                        'remark' => '您添加了下级' . $data['true_name'] . '，扣减' . $system_config['price'] . '报单币.余额' . $system_balance,
                        'create_time' =>  time()
                    );
                    $this->add_system_money_log($money_logdata);
                }
                $userUpdata = array('parent_path' => $user['id'] . ',' . $parent_user['parent_path']);

                $this->user_model->editUser(array('id' => $user['id']), $userUpdata);
                $zhitu = $this->zhitui2($user, $parent_user);
                if ($zhitu) {
                } else {
                    $this->location_href($this->go_url . "/5");
                }
            }
            if (isset($parent_user['parent_id'])) {
                $parent_parent_user = $this->user_model->checkUser(array('id' => $parent_user['parent_id']));
                $this->load->model('user_level_model');
                $user_level = $this->user_level_model->checkUserLevel(array('id' => $parent_user['user_level']));
                $distribution = $this->shouru($user, $parent_user, $parent_parent_user, $user_level['use_id'], false, 3, true, $asjs);
                if ($distribution) {
                } else {
                    $this->location_href($this->go_url . "/5");
                }
            }

            $this->getperformance($user);
            //$this->update_level();
            //先记录下目前
            $this->updatelevel($user);
        } //exit;
        $this->location_href($this->go_url . "/4");
    }
    /**
     * 参数验证
     */
    public function check_param()
    {
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');

        $this->form_validation->set_rules('username', '用户名长度4-12位', 'required|min_length[4]|max_length[12]');
        $this->form_validation->set_rules('password1', '登录密码长度在6-16位', 'required|min_length[6]|max_length[16]');
        $this->form_validation->set_rules('password2', '二级密码长度在6-16位', 'required|min_length[6]|max_length[16]');
        $this->form_validation->set_rules('price', '请填写数字', 'required|numeric');

        if ($this->form_validation->run() == FALSE) {
            $area_array = array();
            if (count($area_array) != 3) {
                $area_array[0] = '110000';
                $area_array[1] = '111000';
                $area_array[2] = '110101';
            }
            $province_area = $area_array[0];
            $city_area = $area_array[1];
            $area_where['parentno'] = 0;
            $area_list = $this->area_model->getArealist($area_where);
            $city_list = $this->area_model->getArealist(array('parentno' => $province_area, 'arealevel' => 2));
            $county_list = $this->area_model->getArealist(array('parentno' => $city_area, 'arealevel' => 3));
            $this->data['area_list'] = $area_list;
            $this->data['city_list'] = $city_list;
            $this->data['county_list'] = $county_list;
            $this->data['parent_id'] = $_POST['parent_id'];
            $this->data['parent_true_name'] = $_POST['parent_true_name'];
            $this->getFora();
            $this->load->view('/admin/user_add',  $this->data);
        } else {
            return true;
        }
    }

    /**
     * @brief 导入功能操作
     * @param Null
     * @par 2016/01/05 Ver 1.00 Created by chenqi
     */
    function excel_into()
    {
        ini_set("max_execution_time", 2400); // s 40 分钟 
        if (!empty($_FILES['code']['name'])) {
            $tmp_file = $_FILES['code']['tmp_name'];
            $file_types = explode(".", $_FILES['code']['name']);
            $file_type = $file_types[count($file_types) - 1];
            if (strtolower($file_type) != "xls") {
                //$this->location_href($this->go_url."/6");
            }
            $savePath = $this->config->config['excel_path'];
            $str = date('Ymdhis');
            $file_name = $str . "." . $file_type;
            if (!copy($tmp_file, $savePath . $file_name)) {
                //$this->location_href($this->go_url."/7");
            }
            $this->load->helper('phpexecl');
            $data = new Spreadsheet_Excel_Reader();
            $data->setOutputEncoding('UTF-8');
            $data->read($savePath . $file_name);
            set_time_limit(20000);
            ini_set("memory_limit", "2000M");
            //			//使用pdo连接数据库
            //			$dsn = "mysql:host=127.0.0.1;dbname=dati;";
            //			$user = "root";
            //			$password = "root";
            //			try{
            //				$dbh = new PDO($dsn,$user,$password);
            //				$dbh->query('set names utf8;');
            //			}catch(PDOException $e) {
            //				$this->location_href($this->go_url."/8");
            //			}
            //			$date = date("Y-m-d H:i:s");
            //			//pdo绑定参数操作
            //			$stmt = $dbh->prepare("insert into timu(title,image,option_a,option_b,option_c,option_d,answer,levels,score,wrong_score,skip_score,share_score,create_time,update_time) values (:title,:image,:option_a,:option_b,:option_c,:option_d,:answer,:levels,:score,:wrong_score,:skip_score,:share_score,:create_time,:update_time)");			
            //			$stmt->bindParam(":title", $title,PDO::PARAM_STR);
            //			$stmt->bindParam(":image", $image,PDO::PARAM_STR);
            //			$stmt->bindParam(":option_a", $option_a,PDO::PARAM_STR);
            //			$stmt->bindParam(":option_b", $option_b,PDO::PARAM_STR);
            //			$stmt->bindParam(":option_c", $option_c,PDO::PARAM_STR);
            //			$stmt->bindParam(":option_d", $option_d,PDO::PARAM_STR);
            //			$stmt->bindParam(":answer", $answer,PDO::PARAM_STR);
            //			$stmt->bindParam(":levels", $levels,PDO::PARAM_STR);
            //			$stmt->bindParam(":score", $score,PDO::PARAM_STR);
            //			$stmt->bindParam(":wrong_score", $wrong_score,PDO::PARAM_STR);
            //			$stmt->bindParam(":skip_score", $skip_score,PDO::PARAM_STR);
            //			$stmt->bindParam(":share_score", $share_score,PDO::PARAM_STR);
            //			$stmt->bindParam(":create_time", $create_time,PDO::PARAM_STR);
            //			$stmt->bindParam(":update_time", $update_time ,PDO::PARAM_STR);
            //使用php-excel-reader读取excel内容
            $user_data = array();
            $data = new Spreadsheet_Excel_Reader();
            $data->setOutputEncoding('UTF-8');
            $data->read($savePath . $file_name);
            for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
                for ($j = 1; $j <= 200000; $j++) {

                    if ($j == 200000) {


                        $user_data[$i]['id'] = $data->sheets[0]['cells'][$i][1];
                        $user_data[$i]['parent_id'] = $data->sheets[0]['cells'][$i][2];
                        $user_data[$i]['password'] = md5($data->sheets[0]['cells'][$i][6]);
                        $user_data[$i]['password2'] = md5($data->sheets[0]['cells'][$i][6]);
                        $user_data[$i]['csg'] = $data->sheets[0]['cells'][$i][18] ? $data->sheets[0]['cells'][$i][18] : '';
                        $user_data[$i]['true_name'] = $data->sheets[0]['cells'][$i][8];
                        $user_data[$i]['username'] = $data->sheets[0]['cells'][$i][5];
                        $user_data[$i]['price'] = $data->sheets[0]['cells'][$i][11];
                        $user_data[$i]['phone'] = $data->sheets[0]['cells'][$i][9] ? $data->sheets[0]['cells'][$i][9] : '';
                        $user_data[$i]['create_time'] =  strtotime($data->sheets[0]['cells'][$i][10]);
                        $user_data[$i]['update_time'] = time();


                        //					$title = $data->sheets[0]['cells'][$i][1];
                        //					$image = $data->sheets[0]['cells'][$i][2];
                        //					$option_a = $data->sheets[0]['cells'][$i][3];
                        //					$option_b = $data->sheets[0]['cells'][$i][4];
                        //					$option_c = $data->sheets[0]['cells'][$i][5];
                        //					$option_d = $data->sheets[0]['cells'][$i][6];
                        //					$answer = $data->sheets[0]['cells'][$i][7];
                        //					$levels = $data->sheets[0]['cells'][$i][8];
                        //					$score = $data->sheets[0]['cells'][$i][9];
                        //					$wrong_score = $data->sheets[0]['cells'][$i][10];
                        //					$skip_score = $data->sheets[0]['cells'][$i][11];
                        //					$share_score = $data->sheets[0]['cells'][$i][12];
                        //					$create_time = time();
                        //					$update_time = time();
                        $this->add_excel($user_data[$i]);
                    }
                }
            }
        }
    }
    /**
     * 添加用户
     */
    public function add_excel($data)
    {

        $this->load->model('user_level_model');
        $user_level = $this->user_level_model->checkUserLevel(array('is_default' => '1'));
        $data['user_level'] = $user_level['id'];


        $add_result = $this->user_model->addUser($data);

        $user = array();
        $parent_user = array();
        $parent_parent_user = array();
        if ($add_result) {
            $user = $this->user_model->checkUser(array('id' => $add_result));
            if ($data['parent_id']) {

                $parent_user = $this->user_model->checkUser(array('id' => $data['parent_id']));
                $zhitu = $this->zhitui2($user, $parent_user);
                if ($zhitu) {
                } else {
                    //$this->location_href($this->go_url."/5");
                }
            }
            if (isset($parent_user['parent_id'])) {
                $parent_parent_user = $this->user_model->checkUser(array('id' => $parent_user['parent_id']));
                $distribution = $this->shouru($user, $parent_user, $parent_parent_user, $parent_user['user_level']);
                if ($distribution) {
                } else {
                    //$this->location_href($this->go_url."/5");
                }
            }
            $this->getperformance($user);
            //$this->update_level();
            $this->updatelevel($user);
        } //exit;
        //$this->location_href($this->go_url."/4");
    }
    /**
     * @brief 导出功能操作
     * @param Null
     * @par 2016/01/05 Ver 1.00 Created by chenqi
     */
    function list_export_excel()
    {
        error_reporting(E_ALL ^ E_NOTICE);
        ini_set('memory_limit', '-1');
        set_time_limit(0);
        $this->load->helper('array_to_excel');

        $user_list = $this->user_model->getUserAll();

        $parent_users = array();
        $order_export = array();
        foreach ($user_list as $key => $value) {
            if ($value['parent_id']) {
                if (isset($parent_users[$value['parent_id']])) {
                    $user_list[$key]['parent_user_name'] = $parent_users[$value['parent_id']]['username'];
                } else {
                    $parent_user = array();
                    $parent_user = $this->user_model->checkUser(array('id' => $value['parent_id']));

                    if (empty($parent_user) || count($parent_user) == 0) {
                        $parent_user = array('username' => '无');
                    }

                    $parent_users[$value['parent_id']] = $parent_user;
                    $value['parent_user_name'] = $parent_users[$value['parent_id']]['username'];
                }
            }
            switch ($value['user_level']) {
                case '1':
                    $value['user_level_name'] = '业务员';

                    break;
                case '2':
                    $value['user_level_name'] = '业务主任';

                    break;
                case '3':
                    $value['user_level_name'] = '业务经理';

                    break;
                case '4':
                    $value['user_level_name'] = '业务高管';
                    break;
                default:
                    $value['user_level_name'] = '';
                    break;
            }
            $value['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
            $value['update_time'] = date('Y-m-d H:i:s', $value['update_time']);
            $order_export[] = array(
                $value['id'], $value['username'], $value['true_name'], $value['phone'], $value['parent_id'], $value['parent_user_name'],
                $value['create_time'],
                $value['update_time'], $value['user_level_name'], $value['money'],
                $value['balance'], $value['system_money'], $value['system_balance'], $value['tixian'], $value['score'], $value['performance'], $value['price'], $value['next_count'], $value['tax'], $value['feiyong'], $value['csg']
            );
        }
        $arr_name = array('ID', '帐号', '姓名', '手机号', '上级ID', '上级昵称', '加入时间', '更新时间', '等级', '总佣金', '佣金余额', '总报单币', '报单币余额', '已提现金额', '积分', '业绩', '本人费用', '直接下级个数', '提现税收', '管理费', '供位');

        export_data_excel($arr_name, $order_export, '用户列表');
    }
    /**
     * 检测用户名是否重复
     */
    public function check_name()
    {
        $success = true;
        $where = array();
        $where['username'] = $_POST['newusername'];
        $user = $this->user_model->checkUser($where);
        if ($user && $user['id'] != $_POST['id']) {
            $success = false;
        }
        echo json_encode($success);
    }
    /**
     * 检测用户名是否重复
     */
    public function check_name2()
    {
        $success = true;
        $where = array();
        $where['username'] = $_POST['username'];
        $user = $this->user_model->checkUser($where);
        if ($user) {
            $success = false;
        }
        echo json_encode($success);
    }
    /**
     * 增加会员报单价格
     */
    public function addprice()
    {
        $data = array();
        $data['success'] = false;
        if ($this->admin['admin_type'] == 'admin' && $this->Isallow('user', 'addprice')) {
            if (empty($_POST['id']) || empty($_POST['money']) || $_POST['money'] <= 0 || !isset($_POST['ansuo'])) {
                $this->data['error'] = '参数错误';
            } else {
                $user = array();
                $parent_user = array();
                $parent_parent_user = array();
                $user_id = $_POST['id'];
                $user = $this->user_model->checkUser(array('id' => $user_id));
                if ($user) {
                    if ($_POST['money'] > $user['price']) {
                        $user['price'] = $_POST['money'] - $user['price'];
                        if ($user['parent_id']) {
                            $parent_user = $this->user_model->checkUser(array('id' => $user['parent_id']));
                            $zhitu = $this->zhitui2($user, $parent_user);
                        }
                        if (isset($parent_user['parent_id'])) {
                            $parent_parent_user = $this->user_model->checkUser(array('id' => $parent_user['parent_id']));
                            $distribution = $this->shouru($user, $parent_user, $parent_parent_user, $parent_user['user_level'], true, 3, true, $_POST['ansuo']);
                        }

                        $this->getperformance($user);
                        //$this->update_level();
                        $this->updatelevel($user);
                        $parent_user = $this->user_model->editUser(array('id' => $user['id']), array('price' => $_POST['money']));
                        $data['success'] = true;
                    } else {
                        $data['error'] = "回填费用不能小于现在费用";
                    }
                } else {
                    $data['error'] = "用户不存在";
                }
            }
        } else {
            $data['error'] = '权限不足';
        }

        echo json_encode($data);
    }

    public function getFora()
    {
        $this->load->model('fora_model');
        $fora = $this->fora_model->getForaAll(array('status' => 1));
        $this->data['fora'] = $fora;
    }
    /**
     * 展示用户团队
     * */
    /**
     * @brief	查找是否有下级
     * @param 	Null
     * @author	Allen
     * @since	2016/08/22 Ver 1.0
     */
    public function findChild(&$arr, $id)
    {
        $childs = array();
        // echo "<pre>";print_r($arr);
        foreach ($arr as $k => $v) {
            if ($v['parent_id'] == $id) {
                $childs[$v['username']] = $v;
            }
        }
        return $childs;
    }

    /**
     * @brief	建立新数组
     * @param 	Null
     * @author	Allen
     * @since	2016/08/22 Ver 1.0
     */
    public function build_tree($rows, $root_id)
    {
        $childs = $this->findChild($rows, $root_id);
        if (empty($childs)) {
            return null;
        }
        foreach ($childs as $k => $v) {
            $rescurTree = $this->build_tree($rows, $v['id']);
            if (null !=  $rescurTree) {
                $childs[$v['username']] = $rescurTree;
            } else {
                $childs[$v['username']] = $v['username'];
            }
        }
        return $childs;
    }

    /**
     * @brief	测试数据
     * @param 	Null
     * @author	Allen
     * @since	2016/08/22 Ver 1.0
     */
    public function team_page()
    {
        ini_set('memory_limit', '-1');


        /**获取关系链数组数据 所有父级
         *
         */

        if (isset($_GET['id']) && $_GET['id']) {

            $id = $_GET['id'];

            $parents_tmp = $this->user_model->getParent(array('id' => $id));

            krsort($parents_tmp);

            $parents = array_values($parents_tmp);

            unset($parents_tmp);
            /**获取关系链数组数据**/
            $chain_list_tmp = $this->user_model->getChainList($id, 'id,username,parent_id,user_level');
            // echo "<pre>";
            // print_r($parents);
            // echo "<pre>";
            // print_r($chain_list_tmp);
            $chain_list = array_merge($parents, $chain_list_tmp);
            // echo "<pre>";
            // print_r($chain_list);
            // exit;
            foreach ($chain_list as $ckey => &$cvalue) {
                $cvalue['username'] = $cvalue['id'] . '/' . $cvalue['username'] . '/' . $cvalue['user_level'];
            }
            if ($chain_list) {
                $team_id = $chain_list[0]['id'];
                $user_nick = $chain_list[0]['username'];
                if (count($chain_list) > 1) {
                    $tree = $this->build_tree($chain_list, $team_id);
                } else {
                    $tree = $user_nick;
                }
                $trees[$user_nick] = $tree;
            } else {
                $trees['无数据'] = '无数据';
            }
        } else {
            $trees['无数据'] = '无数据';
        }

        $this->data['data'] = $trees;

        $this->load->view('/admin/user_team.php', $this->data);
    }

    public function retry_path()
    {
    }

    public function add_path()
    {
        $end_id = isset($_GET['eid']) ? $_GET['eid'] : 0;
        $start_id = isset($_GET['sid']) ? $_GET['sid'] : 0;
        $where = '';
        if ($start_id > -1) {
            $where = 'id >=' . $start_id;
        }
        if ($end_id > 0) {
            $where .= ' and id <=' . $end_id;
        }
        ignore_user_abort(true);
        ini_set('max_execution_time', '0');
        ini_set('memory_limit', '-1');
        $users = $this->user_model->getUserIds($where);
        $num = 0;
        foreach ($users as $k => $v) {
            // if ($v['parent_path']) continue;
            $parent_path = $this->user_model->getParent_id(array('id' => $v['id']));
            $this->user_model->editUser(array('id' => $v['id']), array('parent_path' => $parent_path));
            error_log('parent_path:' . $parent_path . "\n", 3, 'user.log');
            $num++;
        }
        $result = array('code' => 200, 'msg' => '用户id' . $start_id . '到' . $end_id . '执行成功', 'count' => $num);
        echo json_encode($result);
        // foreach ($users as $k => $v) {
        //     // if ($v['parent_path']) continue;
        //     $next_count = $this->user_model->getNextCount($v['id']);
        //     $this->user_model->editUser(array('id' => $v['id']), array('next_count' => $next_count));
        //     echo $next_count . "<br/>";
        //     error_log('next_count:' . $next_count . "\n", 3, 'user.log');
        // }
        // foreach ($users as $k => $v) {
        //     // if ($v['parent_path']) continue;
        //     $next_next_count = $this->user_model->getNextNextCount($v['id']);
        //     $this->user_model->editUser(array('id' => $v['id']), array('next_next_count' => $next_next_count));
        //     echo $next_next_count . "<br/>";
        //     error_log('next_next_count:' . $next_next_count . "\n", 3, 'user.log');
        // }
    }
    public function nextCount()
    {
        $end_id = isset($_GET['eid']) ? $_GET['eid'] : 0;
        $start_id = isset($_GET['sid']) ? $_GET['sid'] : 0;
        $type = isset($_GET['type']) ? $_GET['type'] : 'nextCount';
        $where = array();
        if ($start_id > -1) {
            $where = 'id >=' . $start_id;
        }
        if ($end_id > 0) {
            $where .= ' and id <' . $end_id;
        }
        ignore_user_abort(true);
        ini_set('max_execution_time', '0');
        ini_set('memory_limit', '-1');

        $users = $this->user_model->getUserIds($where);

        $num = 0;
        if ($type == 'nextCount') {
            foreach ($users as $k => $v) {
                // if ($v['parent_path']) continue;
                $next_count = $this->user_model->getNextCount($v['id']);
                $this->user_model->editUser(array('id' => $v['id']), array('next_count' => $next_count));
                // echo $next_count . "<br/>";
                error_log($v['id'] . 'next_count:' . $next_count . "\n", 3, 'user.log');
                $num++;
            }
        } else {
            foreach ($users as $k => $v) {
                // if ($v['parent_path']) continue;
                $next_next_count = $this->user_model->getNextNextCount($v['id']);
                $this->user_model->editUser(array('id' => $v['id']), array('next_next_count' => $next_next_count));
                // echo $next_next_count . "<br/>";
                error_log($v['id'] . 'next_next_count:' . $next_next_count . "\n", 3, 'user.log');
                $num++;
            }
        }
        $result = array('code' => 200, 'msg' => '用户id' . $start_id . '到' . $end_id . '执行成功', 'count' => $num);
        return  json_encode($result);
    }
}
